<?php

namespace backend\modules\Sys\modules\Rbac\modules\Admin\controllers;

use backend\models\c2\entity\rest\BeUser;
use backend\models\c2\search\rest\BeUserSearch;
use common\models\c2\statics\EntityModelStatus;
use common\rest\controllers\AuthController;
use common\rest\models\c2\statics\ResponseDatum;
use Yii;
use yii\web\NotFoundHttpException;

/**
 * Default controller for the `admin` module
 */
class DefaultController extends AuthController
{

    public $modelClass = 'backend\models\c2\entity\rest\BeUser';

    public $serializer = [
        'class' => 'common\rest\components\Serializer',
        'collectionEnvelope' => 'data',
        'modelClass' => 'backend\models\c2\search\rest\BeUserSearch',
    ];

    /**
     * Renders the index view for the module
     * @return \yii\data\ActiveDataProvider
     */
    public function actionIndex()
    {
        $searchModel = new BeUserSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $dataProvider;
    }

    /**
     * @param null $id
     * @return array
     * @throws NotFoundHttpException
     */
    public function actionEdit($id = null)
    {
        /** @var BeUser $model */
        $model = $this->retrieveModel($id);
        if ($model->load(Yii::$app->request->post())) {
            if ($model->save()) {
                return ResponseDatum::getSuccessDatum(['isNewRecord' => $model->isNewRecord, 'primaryKeys' => ['id' => $model->id]]);
            } else {
                return ResponseDatum::getErrorDatum($model->errors);
            }
        }
        return ResponseDatum::getSuccessDatum([
            'inputItems' => $model->buildInputItems(),
            'modelForm' => $model->formName(),
            'isNewRecord' => $model->isNewRecord,
        ]);
    }

    public function actionDelete()
    {
        $params = Yii::$app->request->post();
        $ids = isset($params['ids']) ? $params['ids'] : [];
        $count = BeUser::updateAll(['status' => EntityModelStatus::STATUS_INACTIVE], ['in', 'id', $ids]);
        if ($count) {
            return ResponseDatum::getSuccessDatum($count);
        }
        return ResponseDatum::getErrorDatum($count);
    }

    /**
     * Finds the BeUser model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return array|BeUser
     * @throws NotFoundHttpException
     */
    protected function findModel($id)
    {
        if (($model = BeUser::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}
